//
//  IndexViewController.m
//  parent
//
//  Created by yanzhen on 15/7/16.
//  Copyright (c) 2015年 ci123. All rights reserved.
//

#import "IndexViewController.h"
#import "SignViewController.h"
#import "CityViewController.h"
#import "MJRefresh.h"
#import "NetWorkManager.h"
#import "BDKNotifyHUD.h"
#import "UserDao.h"
#import "PopUIManager.h"
#import "JsonUtil.h"
#import "UIImageView+WebCache.h"
#import "DetailNewViewController.h"
#import "HomeItemViewCell.h"
#import "AFAppClient.h"
#import "HealthViewController.h"
#import "ForumViewCell.h"
#import "AJWDraggableDroppable.h"
#import "UMSocial.h"
#import "Config.h"
#import "MyloginViewController.h"
#import "MWPhotoBrowser.h"
#import "TBXML+HTTP.h"
#import "ChatViewController.h"

@interface IndexViewController ()<AJWDraggableDroppableDelegate,MWPhotoBrowserDelegate>
@property (weak, nonatomic) IBOutlet UILabel *aqi_txt;
@property (weak, nonatomic) IBOutlet UIImageView *redImg;

@property (weak, nonatomic) IBOutlet UILabel *quality_txt;

@property (weak, nonatomic) IBOutlet UILabel *today_tmp;
@property (weak, nonatomic) IBOutlet UILabel *tomorrow_tmp;
@property (weak, nonatomic) IBOutlet UILabel *now_weath;
@property (weak, nonatomic) IBOutlet UILabel *now_tmp;
@property (weak, nonatomic) IBOutlet UIImageView *now_img;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIButton *oneCall;
@property NSMutableArray *topicData;
@property NSString *avatar_header;
@property BDKNotifyHUD *hud;
@property NSArray *data;
@property NSString *city;
@property (weak, nonatomic) IBOutlet UILabel *checkDate;
@property (strong, nonatomic) AJWDraggableDroppable *dragDropController;
@property (weak, nonatomic) IBOutlet UIScrollView *scrollview;
@property (weak, nonatomic) IBOutlet UILabel *xya;
@property (weak, nonatomic) IBOutlet UILabel *xtang;
@property (weak, nonatomic) IBOutlet UILabel *xyang;
@property (weak, nonatomic) IBOutlet UILabel *vlv;

@property (weak, nonatomic) IBOutlet UIImageView *dengpao;
@property (weak, nonatomic) IBOutlet UIImageView *yellow_coffe;
@property (weak, nonatomic) IBOutlet UIImageView *xiaohai;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *rightTo1;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *rightTo0;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *rightTo2;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *rightTo3;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *tableviewHieght;
@property UIButton *button;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *containerViewHeight;

@property NSArray *picArray;

@property MWPhotoBrowser *browser;

@property NSUInteger currentIndex;

@end

@implementation IndexViewController
-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
     //[_scrollview setContentSize:CGSizeMake(APP_SCREEN_WIDTH, 1444)];
}

-(void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    //[_scrollview setContentSize:CGSizeMake(APP_SCREEN_WIDTH, 1444)];

}
- (void)viewDidLoad {
    [super viewDidLoad];
    //self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationItem.title=@"首页";
    // Do any additional setup after loading the view from its nib.
    [self createTopBar];
    if(APP_SCREEN_WIDTH==320){
        _rightTo0.constant= 4;
        _rightTo1.constant = 4;
        _rightTo2.constant = 4;
        _rightTo3.constant = 4;
    }

    _data = @[@{@"type":@(1),@"image":@"文化养老",@"title":@"来自文化养老",@"content":@"张扬你的个性 积极享受快乐",@"color":RGBACOLOR(254,199,8, 1)},
              @{@"type":@(2),@"image":@"智慧生活",@"title":@"来自智慧生活",@"content":@"依托云端服务 物联创新生活",@"color":RGBACOLOR(252,130,7, 1)},
              @{@"type":@(3),@"image":@"健康养生",@"title":@"来自健康养生",@"content":@"一手养生资讯 潮流健康生活",@"color":RGBACOLOR(123,209,4, 1)},
              @{@"type":@(4),@"image":@"时尚汇",@"title":@"来自时尚汇",@"content":@"时尚JOJO 坐镇聊穿衣",@"color":RGBACOLOR(252,108,173, 1)},
              @{@"type":@(5),@"image":@"云律师",@"title":@"来自云律师",@"content":@"世界律师平台 全球各地贴身保护",@"color":RGBACOLOR(25,197,241, 1)}
              ];
    _topicData = [[NSMutableArray alloc]init];
    _tableView.scrollEnabled = NO;
    [_tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    _tableView.headerPullToRefreshText = @"下拉刷新";
    _tableView.headerReleaseToRefreshText = @"松开刷新";
    _tableView.headerRefreshingText = @"正在刷新...";
    [_tableView headerBeginRefreshing];
    _city = @"南京";
    _redImg.userInteractionEnabled = YES;
    UITapGestureRecognizer *rec = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(health:)];
    [_redImg addGestureRecognizer:rec];
    
    self.dragDropController = [[AJWDraggableDroppable alloc] initWithReferenceView:self.view];
    self.dragDropController.delegate = self;
    [self.dragDropController registerDraggableView:_oneCall];
    [self getWeather];
    [self getHealth];
}
-(void)getHealth
{
    if([[Config Instance]isCookie]){
    [[AFAppClient sharedManager]getWithURL:[NSString stringWithFormat:@"%@%@",SERVER_URL_NEW,kGetHealthNos] withParameters:@{@"uid":@([[Config Instance]getUID])} success:^(NSDictionary *responseObject) {
        
        if([[responseObject objectForKey:@"code"]integerValue]==1){
            NSArray *result = [responseObject objectForKey:@"result"];
            
            NSDictionary *info = [result objectAtIndex:0];
            NSString *number = [info objectForKey:@"number"];
            [self getXMLDATA:number];
        }else {
            
        }
    } failure:^(NSError *error) {
        
    }];
    }

}
-(void)getXMLDATA:(NSString *)peopleNo
{
    //http://www.hanncloud.com/api.asp?personid=342530198606130814
    TBXML *tbxml = [[TBXML alloc]initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@?personid=%@",GET_HEALTH_URL,peopleNo]] success:^(TBXML *tbxml) {
        TBXMLElement *root = tbxml.rootXMLElement;
        TBXMLElement *series = [TBXML childElementNamed:@"series" parentElement:root];
        
        //身高表
        TBXMLElement *he = [TBXML childElementNamed:@"he" parentElement:series];
        NSString *text = [TBXML textForElement:he];
        if(text && [text isEqualToString:@"false"]){
            
        }else{
            TBXMLElement *record0 = [TBXML childElementNamed:@"record" parentElement:he ];
            TBXMLElement *height = [TBXML childElementNamed:@"value" parentElement:record0];
            NSString *str_height = [TBXML textForElement:height];
            //            _height.text = [NSString stringWithFormat:@"%@==",str_height];
            
            TBXMLElement *checkdate = [TBXML nextSiblingNamed:@"value" searchFromElement:height];
            NSString *str_checkdate = [TBXML textForElement:checkdate];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                NSDateFormatter *format =  [[NSDateFormatter alloc]init];
                [format setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
                
                NSDate *dateN = [format dateFromString:str_checkdate];
                [format setDateFormat:@"yyyy年MM月dd日"];
                [_checkDate setText:[NSString stringWithFormat:@"%@体检数据",[format stringFromDate:dateN] ]];
            });
            
        }

        
        //血糖表
        TBXMLElement *bg = [TBXML childElementNamed:@"bg" parentElement:series];
        NSString *text4 = [TBXML textForElement:bg];
        if(text4 &&[text4 isEqualToString:@"false"]){
            
        }else{
            TBXMLElement *record0 = [TBXML childElementNamed:@"record" parentElement:bg ];
            TBXMLElement *bg = [TBXML childElementNamed:@"value" parentElement:record0];
            NSString *str_bg = [TBXML textForElement:bg];
            dispatch_async(dispatch_get_main_queue(), ^{
                _xtang.text = [NSString stringWithFormat:@"血糖：%@",str_bg];
            });
        }
        
        //血压表
        TBXMLElement *bp = [TBXML childElementNamed:@"bp" parentElement:series];
        NSString *text5 = [TBXML textForElement:bp];
        if(text5 &&[text5 isEqualToString:@"false"]){
            
        }else{
            TBXMLElement *record0 = [TBXML childElementNamed:@"record" parentElement:bp ];
            TBXMLElement *sbp = [TBXML childElementNamed:@"value" parentElement:record0];
            NSString *str_sbp = [TBXML textForElement:sbp];
            TBXMLElement *dbp = [TBXML nextSiblingNamed:@"value" searchFromElement:sbp];
            NSString *str_dbp = [TBXML textForElement:dbp];
            dispatch_async(dispatch_get_main_queue(), ^{
                _xya.text = [NSString stringWithFormat:@"血压：%@ %@",str_sbp,str_dbp];
            });
            
        }
        //血氧表
        TBXMLElement *po = [TBXML childElementNamed:@"po" parentElement:series];
        NSString *text6 = [TBXML textForElement:po];
        if(text6 &&[text6 isEqualToString:@"false"]){
            
        }else{
            TBXMLElement *record0 = [TBXML childElementNamed:@"record" parentElement:po ];
            TBXMLElement *spo2 = [TBXML childElementNamed:@"value" parentElement:record0];
            NSString *str_spo2 = [TBXML textForElement:spo2];
            dispatch_async(dispatch_get_main_queue(), ^{
                _xyang.text = [NSString stringWithFormat:@"血氧：%@",str_spo2];
            });
        }
        
        //心电表
        TBXMLElement *ecg = [TBXML childElementNamed:@"ecg" parentElement:series];
        NSString *text7 = [TBXML textForElement:ecg];
        if(text7 &&[text7 isEqualToString:@"false"]){
            
        }else{
            TBXMLElement *record0 = [TBXML childElementNamed:@"record" parentElement:ecg ];
            TBXMLElement *ecg = [TBXML childElementNamed:@"value" parentElement:record0];
            NSString *str_ecg = [TBXML textForElement:ecg];
            dispatch_async(dispatch_get_main_queue(), ^{
                _vlv.text = [NSString stringWithFormat:@"心率：%@",str_ecg];
            });
        }
        
        /*
         TBXMLElement *author = [TBXML childElementNamed:@"author" parentElement:root];
         NSString *name = [TBXML valueOfAttributeNamed:@"name" forElement:author];
         NSLog(@"author:%@", name);
         TBXMLElement *book = [TBXML childElementNamed:@"book" parentElement:author];
         TBXMLElement *descriptionElem = [TBXML childElementNamed:@"description" parentElement:book];
         NSString * description = [TBXML textForElement:descriptionElem];
         NSLog(@"author:%@", description);
         */
    } failure:^(TBXML *tbxml, NSError *error) {
        debugLog(@"获取数据失败~");
    }];
}

-(void)scaleIt
{
    float scale = .85;
    [_dengpao setFrame:CGRectMake(_dengpao.origin.x, _dengpao.origin.y, _dengpao.size.width*scale, _dengpao.size.height*scale)];
    [_yellow_coffe setFrame:CGRectMake(_yellow_coffe.origin.x, _yellow_coffe.origin.y, _yellow_coffe.size.width*scale, _yellow_coffe.size.height*scale)];
    [_xiaohai setFrame:CGRectMake(_xiaohai.origin.x, _xiaohai.origin.y, _xiaohai.size.width*scale, _xiaohai.size.height*scale)];
}
-(void)health:(id)sender
{
    if([[Config Instance]isCookie]){
        HealthViewController *view = [[HealthViewController alloc]init];
        view.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:view animated:YES];
    }else{
        
       MyloginViewController *login = [MyloginViewController shareController];
        
        UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:login];
        [self presentViewController:nav animated:YES completion:^{
            
        }];

    }
}
//================顶部刷新，获取最新动态=========================
//首次进入会自动执行一次获取最新动态
- (void)headerRereshing
{
    if ([NetWorkManager connectedToNetwork]) {
        [self getArticles:@"new" withBaseid:0];
    }else{
        //没有网络的情况下，加载本地缓存数据
        [_hud presentWithDuration:1.0f speed:0.5f inView:self.view completion:^{
            [_hud removeFromSuperview];
        }];
        
    }
}
- (IBAction)callNow:(id)sender {
    debugLog(@"Call now~~");
//    [UMSocialSnsService presentSnsIconSheetView:self
//                                         appKey:@"507fcab25270157b37000010"
//                                      shareText:@"你要分享的文字"
//                                     shareImage:[UIImage imageNamed:@"AppIcon"]
//                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToLWTimeline,UMShareToWechatSession,UMShareToSina,UMShareToQQ,nil]
//                                       delegate:self];
    UIApplication *myApp = [UIApplication sharedApplication];
    NSString *theCall = [NSString stringWithFormat:@"tel://4000128815"];
    NSLog(@"making call with %@",theCall);
    [myApp openURL:[NSURL URLWithString:theCall]];
}
-(void)createTopBar
{
    /*
    UIBarButtonItem *leftItem= [[UIBarButtonItem alloc]initWithTitle:@"南京" style:UIBarButtonItemStylePlain target:self action:@selector(leftItemClick:)];
     */
    UIBarButtonItem *negativeSpacer1 = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    [negativeSpacer1 setWidth:-30];
     _button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 80, 44)];
    float fontsize=16.0f;

    _button.titleLabel.font = [UIFont systemFontOfSize:fontsize];
    [_button setTitleColor:UIColorMake(126, 126, 126) forState:UIControlStateNormal];
    [_button setTitle:@"南京" forState:UIControlStateNormal];
    _button.showsTouchWhenHighlighted = YES;
    [_button setBackgroundColor:[UIColor clearColor]];
    [_button setImage:[[UIImage imageNamed:@"下括号"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]  forState:UIControlStateNormal];
    [_button addTarget:self action:@selector(leftItemClick:) forControlEvents:UIControlEventTouchUpInside];
    _button.imageEdgeInsets = UIEdgeInsetsMake(0., _button.frame.size.width - 15., 0., 0.);
    _button.titleEdgeInsets = UIEdgeInsetsMake(0., 0., 0., 0);
    self.navigationItem.leftBarButtonItems = [NSArray arrayWithObjects:negativeSpacer1,  [[UIBarButtonItem alloc] initWithCustomView:_button],nil];
    
    //self.navigationItem.leftBarButtonItem = leftItem;
    
    
    self.navigationItem.title = @"首页";
    
    
    UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    [negativeSpacer setWidth:-17];
    UIBarButtonItem *rightItem =[[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"签到新"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(rightItemClick:)];
     self.navigationItem.rightBarButtonItems = [NSArray arrayWithObjects:negativeSpacer,rightItem,nil];
    // self.navigationItem.rightBarButtonItem = rightItem;
    
}

-(void)viewWillAppear:(BOOL)animated
{
    id cityId = [[NSUserDefaults  standardUserDefaults] objectForKey:@"city"];
    NSString *mmcity = [[NSUserDefaults  standardUserDefaults] objectForKey:MMLastCity];
    if(cityId!=nil){
         NSString *city = [NSString stringWithFormat:@"%@", cityId];
        if(![_city isEqualToString:city]){
            _city = city;
            [self getWeather];
            [_button setTitle:city forState:UIControlStateNormal];
        }
    }else{
        if(mmcity!=nil){
            NSString *t_city = [mmcity substringToIndex:mmcity.length-1];
            if(![_city isEqualToString:t_city]){
                _city = t_city;
                [self getWeather];
                [_button setTitle:t_city forState:UIControlStateNormal];
            }
        }else{
            [self getWeather];
        }
    }
    
}

-(void)leftItemClick:(id)sendere
{
    CityViewController *cityView = [[CityViewController alloc]init];
    cityView.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:cityView animated:YES];
}

-(void)rightItemClick:(id)sender
{
    if(![[Config Instance]isCookie]){
        MyloginViewController *login = [MyloginViewController shareController];
        
        UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:login];
        [self presentViewController:nav animated:YES completion:^{
            
        }];
    }else{
        SignViewController *sign = [[SignViewController alloc]init];
        sign.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:sign animated:YES];
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.01f;
}

-(void)getArticles:(NSString*)requestType withBaseid:(NSUInteger)baseid
{
    //NSString* uid = [NSString stringWithFormat:@"%ld",[[UserDao getInstance] getUserId]];
    //NSString* utype = @"1";
    NSUInteger is_rec= 0;
    
    NSDictionary *temp_dict = [[NSDictionary alloc]initWithObjectsAndKeys:@(0),@"posttype",requestType,@"dir",@(baseid), @"baseid",@(1),@"is_top", nil];
    
    
    PopUIManager *popUIMgr = [PopUIManager getInstanse];
    [popUIMgr showWaitingUI:self.view];
    
    [[AFAppClient sharedManager]getWithURL:[NSString stringWithFormat:@"%@%@",SERVER_URL_NEW,API_USER_GET_ARTICLES] withParameters:temp_dict success:^(NSDictionary *dict) {
        [popUIMgr removeWaitingUI];
        if ([requestType isEqualToString:@"new"]) {
            [self.tableView headerEndRefreshing];
        }else if ([requestType isEqualToString:@"old"]){
            [self.tableView footerEndRefreshing];
            
        }
        if ([[dict objectForKey:@"ret"] integerValue]== 1) {
            NSUInteger retCode = [[dict objectForKey:@"retCode"] integerValue];
            switch (retCode) {
                case 1:
                {
                    _avatar_header = [dict objectForKey:@"avatar_header"];
                    if ([requestType isEqualToString:@"new"]) { //下拉 获取最新数据的回调
                        
                        [_topicData removeAllObjects];
                        
                    }
                    NSArray *posts = [dict objectForKey:@"posts"];
                    for (NSDictionary *item in posts) {
                        [_topicData addObject:item];
                    }
                    [_tableView reloadData];
                    [self updateTableHeight];
                    break;
                }
                case 10020:
                {
                    [_hud setImage:[UIImage imageNamed:@"Checkmark"]];
                    [_hud setText:@"没有更多数据了"];
                    [_hud presentWithDuration:1.0 speed:.5 inView:self.view completion:^{
                        
                    }];
                    break;
                }
                    
                default:
                    break;
            }
            
        }else{
            [popUIMgr popAlertView:nil title:@"提示" message:@"数据解析错误" cancelButtonTitle:@"确定"];
        }
    } failure:^(NSError *error) {
        [popUIMgr removeWaitingUI];
        if ([requestType isEqualToString:@"new"]) {
            
            [self.tableView headerEndRefreshing];
            
        }else if ([requestType isEqualToString:@"old"]){
            
            [self.tableView footerEndRefreshing];
            
        }
        [popUIMgr popAlertView:nil title:@"提示" message:@"网络连接出错" cancelButtonTitle:@"确定"];
    }];
    
}
-(void)updateTableHeight
{
    NSUInteger total=0;
    for (NSUInteger i=0;i<[_topicData count]; i++) {
        total+=[self getHeightByIndex:i];
    }
    _tableviewHieght.constant = total;
    _containerViewHeight.constant = total+273;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *CellIdentifier = @"HomeItemViewCell";
    HomeItemViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        @try{
            NSArray *nibArr = [[NSBundle mainBundle]loadNibNamed:@"HomeItemViewCell" owner:self options:nil];
            cell = (HomeItemViewCell *)[nibArr objectAtIndex:0];
        }
        @catch(NSException *exception) {
            NSLog(@"exception:%@", exception);
        }
        @finally {
            
        }
//        cell = [[HomeItemViewCell alloc]init];
        [cell setAccessoryType:UITableViewCellAccessoryNone];
    }
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    NSDictionary *article;
    article = [_topicData objectAtIndex:indexPath.row];
    
    NSUInteger type = [[article objectForKey:@"type"]integerValue];
    for (NSDictionary *dict in _data) {
        if(type == [[dict objectForKey:@"type"]integerValue]){
            //cell.forumIcon.image = [UIImage imageNamed:[dict objectForKey:@"image"]];
            cell.forumTitle.text = [dict objectForKey:@"title"];
            cell.forumTitle.textColor = [dict objectForKey:@"color"];
            break;
        }
    }
    NSString *avatar =[article objectForKey:@"author_avatar"];
    [cell.avatar sd_setImageWithURL:[NSURL URLWithString:avatar] placeholderImage:[UIImage imageNamed:@"default_circle_icon"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
    }];
    cell.avatar.layer.cornerRadius = 16.5;
    cell.avatar.layer.masksToBounds = YES;
    
    cell.avatar.userInteractionEnabled = YES;
    cell.avatar.tag = indexPath.row;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(chatView:)];
    [cell.avatar addGestureRecognizer:tap];
    
    NSString *author_name = [article objectForKey:@"author_name"];
    [cell.author setText:author_name];
    
    NSString *title = [article objectForKey:@"title"];
    cell.title.text = title;
    
    NSString *post_time = [article objectForKey:@"new_post_time"];
    cell.time.text = post_time;
    
    NSString *relpynum = [article objectForKey:@"replynum"];
    cell.replyNum.text = [NSString stringWithFormat:@"%@",relpynum];
    
   // NSString *transfernum = [article objectForKey:@"transfernum"];
   // cell.transferNum.text = [NSString stringWithFormat:@"%@",transfernum];
    
    NSString *goodnum = [article objectForKey:@"goodnum"];
    cell.goodNum.text = [NSString stringWithFormat:@"%@",goodnum];
    
    NSString *city = [article objectForKey:@"author_city"];
    cell.city.text = city;
    
    NSString *sex =[NSString stringWithFormat:@"%@", [article objectForKey:@"author_sex"]];
   
    if([sex isEqualToString:@"1"]){
        cell.sexImg.image = [UIImage imageNamed:@"man"];
    }else{
        cell.sexImg.image = [UIImage imageNamed:@"woman"];
    }
    
    NSArray *pics = [article objectForKey:@"pics"];
    if(pics&& [pics count]>0){
//        [cell.picsView setHidden:NO];
//        [cell.picsView setFrame:CGRectMake(10, 87, 300, 83)];
        cell.picViewHight.constant = 80 + (80+10)*(([pics count]-1)/3);
        NSArray *subviews = [cell.picsView subviews];
        for (UIView *v in subviews) {
            [v removeFromSuperview];
        }
        int imageTag = 100 * indexPath.row;
        for (NSUInteger i=0; i<[pics count]; i++) {
            NSString *ul = [pics objectAtIndex:i];
            NSUInteger pic_width = 80;
            UIImageView *image = [[UIImageView alloc]initWithFrame:CGRectMake(i%3*(pic_width+6), ((i/3)*(pic_width+6)), pic_width, pic_width)];
            [image setContentMode:UIViewContentModeScaleAspectFill];
            image.clipsToBounds  = YES;
            image.userInteractionEnabled = YES;
            UITapGestureRecognizer *ges=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showImages:)];
            [image addGestureRecognizer:ges];
            image.tag = imageTag;
            imageTag++;
            [image sd_setImageWithURL:[NSURL URLWithString:ul] placeholderImage:nil];
            [cell.picsView addSubview:image];
        }
    }else{
//        [cell.picsView setHidden:YES];
        cell.picViewHight.constant = 0;
    }
    
    cell.shareView.userInteractionEnabled = YES;
    UITapGestureRecognizer *gest = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clickShare:)];
    [cell.shareView addGestureRecognizer:gest];
    
    cell.goodView.userInteractionEnabled = YES;
    UITapGestureRecognizer *gest1 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(goods:)];
    [cell.goodView addGestureRecognizer:gest1];
    cell.goodView.tag =[[article objectForKey:@"id"]integerValue];
    
    return cell;
}

-(void)chatView:(UITapGestureRecognizer*)rec
{
    UIView *view = [rec view];
    NSUInteger tag = [view tag];
    NSDictionary *article = [_topicData objectAtIndex:tag];
    
    ChatViewController *chatVC = [[ChatViewController alloc] initWithChatter:[article objectForKey:@"author_id"] isGroup:NO];
    //            chatVC.title = [[UserProfileManager sharedInstance] getNickNameWithUsername:buddy.username];
    chatVC.title = [article objectForKey:@"author_name"];
    chatVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:chatVC animated:YES];
}

-(void)goods:(UITapGestureRecognizer*)sender
{
    if([[Config Instance]isCookie]){
        UIView *view = [sender view];
        NSUInteger tag = [view tag];
        if(tag>0){
            PopUIManager *popUIMgr = [PopUIManager getInstanse];
            [popUIMgr showWaitingUI:self.view];
            [[AFAppClient sharedManager]getWithURL:[NSString stringWithFormat:@"%@%@",SERVER_URL_NEW,kUserPostGood] withParameters:@{@"uid":@([[Config Instance]getUID]),@"pid":@(tag)} success:^(NSDictionary *responseObject) {
                [popUIMgr removeWaitingUI];
                [_tableView headerBeginRefreshing];
            } failure:^(NSError *error) {
                [popUIMgr removeWaitingUI];
            }];
        }else{
            
        }

    }else{
        
        MyloginViewController *login = [MyloginViewController shareController];
        
        UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:login];
        [self presentViewController:nav animated:YES completion:^{
            
        }];
        
    }
   }
-(void)clickShare:(id)sender
{
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"55a73f3a67e58e7b700001c9"
                                      shareText:@"阿莱回家，国内最大的中老年人线上交流平台，www.zgyxyl.com"
                                     shareImage:[UIImage imageNamed:@"share_icon"]
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent,UMShareToWechatTimeline,UMShareToWechatSession,UMShareToQQ,UMShareToQzone,nil]
                                       delegate:self];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"%@",indexPath);
    //该方法响应列表中行的点击事件
    NSInteger row = indexPath.row;
    NSDictionary *dict= [_topicData objectAtIndex:row];
    
    NSUInteger pid = [[dict objectForKey:@"id"]integerValue ];
    DetailNewViewController *detail = [[DetailNewViewController alloc]init];
    detail.msgId = [NSString stringWithFormat:@"%ld",pid];
    detail.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:detail animated:YES];
    
    
}
-(NSUInteger)getHeightByIndex:(NSUInteger)index
{
    NSDictionary *article;
    article = [_topicData objectAtIndex:index];
    NSArray *pics = [article objectForKey:@"pics"];
    if(pics&& [pics count]>0){
        NSUInteger length = [pics count];
        return 134+80 + (80+6)*((length-1)/3) ;
    }else{
        return 134;
    }
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [_topicData count];
}

//设置Cell行高
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return [self getHeightByIndex:indexPath.row];
}

-(void)getWeather
{
    NSDictionary *param = @{@"city":_city,@"key":WEATH_KEY};
    _aqi_txt.text = @"--";
    _quality_txt.text = @"--";
    _today_tmp.text = @"--";
    _tomorrow_tmp.text = @"--";
    _now_weath.text = @"--";
    _now_tmp.text = @"--";
    [[AFAppClient sharedManager]getWithURL:[NSString stringWithFormat:@"%@",GET_WEATH_URL] withParameters:param success:^(NSDictionary* dict) {
        if(dict){
            NSArray *infos = [dict objectForKey:@"HeWeather data service 3.0"];
            NSDictionary *info = [infos objectAtIndex:0];
            if([NSNull null] != [[[info objectForKey:@"aqi"]objectForKey:@"city"]objectForKey:@"aqi"]){
                NSString *aqi = [[[info objectForKey:@"aqi"]objectForKey:@"city"]objectForKey:@"aqi"];//空气指数
                _aqi_txt.text = aqi;
            }
            if([NSNull null] != [[[info objectForKey:@"aqi"]objectForKey:@"city"]objectForKey:@"qlty"]){
                NSString *qlty =[[[info objectForKey:@"aqi"]objectForKey:@"city"]objectForKey:@"qlty"];//空气质量
                _quality_txt.text = qlty;
            }
            
            NSArray *daily_forecast = [info objectForKey:@"daily_forecast"];
            NSDictionary *today = [daily_forecast objectAtIndex:0];
            if([NSNull null] != [[today objectForKey:@"tmp"]objectForKey:@"max"]){
            NSString *today_tmp_max = [[today objectForKey:@"tmp"]objectForKey:@"max"];
            NSString *today_tmp_min= [[today objectForKey:@"tmp"]objectForKey:@"min"];
            _today_tmp.text = [NSString stringWithFormat:@"今天 %@°%@°",today_tmp_max,today_tmp_min];
           
            }
            NSDictionary *tomorrow = [daily_forecast objectAtIndex:1];
            if([NSNull null] != [[tomorrow objectForKey:@"tmp"]objectForKey:@"max"]){
            NSString *tomorrow_tmp_max = [[tomorrow objectForKey:@"tmp"]objectForKey:@"max"];
            NSString *tomorrow_tmp_min= [[tomorrow objectForKey:@"tmp"]objectForKey:@"min"];
            _tomorrow_tmp.text = [NSString stringWithFormat:@"明天 %@°%@°",tomorrow_tmp_max,tomorrow_tmp_min];
            }
             NSDictionary *now = [info objectForKey:@"now"];
            if([NSNull null] != [[now objectForKey:@"cond"]objectForKey:@"txt"]){
                 
                 NSString *now_wea_txt = [[now objectForKey:@"cond"]objectForKey:@"txt"];
                 _now_weath.text = now_wea_txt;
            }
            NSString *now_wea_code =[NSString stringWithFormat:@"w%@", [[now objectForKey:@"cond"]objectForKey:@"code"]];
            _now_img.image = [UIImage imageNamed:now_wea_code];
            
            if([NSNull null] != [now objectForKey:@"tmp"]){
                NSString *now_tmp_txt = [now objectForKey:@"tmp"];
                _now_tmp.text = [NSString stringWithFormat:@"%@°",now_tmp_txt];
            }
        }
    } failure:^(NSError *error) {
        debugLog(@"%@",error);
    }];
}

/*
 */
//显示大图
-(void)showImages:(UITapGestureRecognizer *)tap{
    UIView *view = [tap view];
    NSUInteger index = view.tag/100;
    NSDictionary *article;
    
    _currentIndex = index;
    
    NSInteger i = view.tag % 100;
    
   // if(_browser == nil) {
    _browser = [[MWPhotoBrowser alloc] initWithDelegate:self];
    _browser.displayActionButton = NO;
    _browser.displayNavArrows = YES;
    _browser.enableGrid = NO;
   // }
    
    [_browser setCurrentPhotoIndex:i];
    UINavigationController *nc = [[UINavigationController alloc] initWithRootViewController:_browser];
    nc.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    [self presentViewController:nc animated:YES completion:nil];
}

#pragma mark - MWPhotoBrowserDelegate
- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser {
    NSDictionary *article = [_topicData objectAtIndex:_currentIndex];
    NSArray *pics = [article objectForKey:@"pics"];
    return pics.count;
}

- (MWPhoto *)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index {
    NSDictionary *article = [_topicData objectAtIndex:_currentIndex];
    NSArray *pics = [article objectForKey:@"pics"];
    if (index < pics.count)
        return [MWPhoto photoWithURL:[NSURL URLWithString:[pics objectAtIndex:index]]];
    return nil;
}

- (MWPhoto *)photoBrowser:(MWPhotoBrowser *)photoBrowser thumbPhotoAtIndex:(NSUInteger)index {
    NSDictionary *article = [_topicData objectAtIndex:_currentIndex];
    NSArray *pics = [article objectForKey:@"pics"];
    if (index < pics.count)
        return [MWPhoto photoWithURL:[NSURL URLWithString:[pics objectAtIndex:index]]];
    return nil;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
